package com.adingxiong.cft.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @ClassName NettyServer
 * @Description TODO
 * @Author xiongchao
 * @Date 2021/4/8 13:28
 **/
@Slf4j
@Component
public class NettyServer implements CommandLineRunner {

    private static NettyServer nettyServer;

    private ServerBootstrap server;

    private EventLoopGroup group;

    private EventLoopGroup work;

    private ChannelFuture future;

    @Value("${netty.tcp.server.port}")
    private int port;

    public static class SingleNettyServer {
        static  final  NettyServer instance  = new NettyServer();
    }

    public static NettyServer getInstance () {
        return SingleNettyServer.instance;
    }

    @PostConstruct
    public void init (){
        nettyServer = this;
    }


    @Override
    public void run(String... args)  {

        server = new ServerBootstrap();
        group = new NioEventLoopGroup();
        work = new NioEventLoopGroup();
        try {
            server.group(group,work);

            server.channel(NioServerSocketChannel.class);
            server.childHandler(new WSServerInitializer());

            log.info("通道配置完成");

            this.future  = server.bind(nettyServer.port);
            log.info("netty server 启动成功 端口为 :{}",nettyServer.port);


            //等待服务关闭
            this.future.channel().closeFuture().sync();
        } catch ( Exception e) {
            e.printStackTrace();
            log.error("websocket 启动异常 :{}" ,e.getMessage());
        } finally {
            group.shutdownGracefully();
            work.shutdownGracefully();
        }
    }
}
